package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 *
 * @Title: 获取录音接口*
 * @Description: 调用电信获取录音，添加至record和event表
 * @Author: admin*
 * @Date 2022/9/26 20:26
 *
 */
class apiGetCallRecord implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetCallRecord.class);

    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = httpServletRequest.getMethod();


        // 初始化返回参数
        String Syncpram = "";
        String Retupram = "";
        if (getMethod.equals("GET")) {
            Syncpram = httpServletRequest.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }

            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        net.sf.json.JSONObject inJson = net.sf.json.JSONObject.fromObject(Syncpram);
        String  beginTime = inJson.getString("beginTime");
        String endTime = inJson.getString("endTime");

        //获取调用密钥及地址
        String AccountID = KHDBConfig.getParam(eliteBean, "7M-ACC");
        String APISecret = KHDBConfig.getParam(eliteBean, "7M-KEY");
        String APIURL = KHDBConfig.getAPIURL(eliteBean, "DX-RECORD-URL");
        log.debug("调用参数" + AccountID + "|" + APISecret + "|" + APIURL);

        //获取当前日期
        Date date1 = new Date();
        //将时间格式化成yyyy-MM-dd HH:mm:ss的格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");

        //创建Calendar实例
        Calendar cal = Calendar.getInstance();
        //设置当前时间
        cal.setTime(date1);

        //同理增加一天的方法：
        cal.add(Calendar.DATE, -1);

        /**
        String beginTime = format.format(cal.getTime());
        String endTime = format2.format(cal.getTime());
             **/
        //测试
        //beginTime = '2022-09-30 00:00:00';
        //endTime = '2022-09-30 23:59:59';
        log.debug("开始时间" + beginTime + "|结束时间" + endTime);

        try {
            int i = 0;
            int page = 1;
            while (i == 0) {
                log.debug("开始获取第" + page + "页数据");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String date = sdf.format(new Date());
                String bBase64 = AccountID + ":" + date;
                String Authorization = KHUtil.getbase64(bBase64);

                // 处理头文件
                Map<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("Accept", "application/json");
                headerMap.put("Content-Type", "application/json");
                headerMap.put("Authorization", Authorization);

                // sig的值为 32位大写MD5加密 （帐号Id + 帐号APISecret +时间戳）
                String bSign = AccountID + APISecret + date;
                String sign = KHUtil.getMD5(bSign).toUpperCase();

                String postURL = APIURL + "/" + AccountID + "?sig=" + sign;
                JSONObject postBody = new JSONObject();
                postBody.put("beginTime", beginTime);
                postBody.put("endTime", endTime);
                postBody.put("getAll", true);
                postBody.put("page", page);
                postBody.put("pageSize", "1000");
                log.debug("发送请求体：" + postBody.toString());

                // 调用API
                String postResult = Util.doHttpPostUseHead(postURL, postBody.toString(), "UTF-8", 120000, 0, headerMap);
                //log.debug("返回结果："+postResult);

                JSONObject dataJson = JSONObject.fromObject(postResult);
                Boolean re_succ = dataJson.getBoolean("success");
                int re_count = dataJson.getInt("count");
                log.debug("是否成功调用：" + re_succ + "|" + "当日总条数：" + re_count);

                int re_data = 0;
                if (re_succ) {
                    JSONArray dataArr = dataJson.getJSONArray("data");
                    re_data = dataArr.size();
                    log.debug("本次获取数据条数：" + re_data);
                    for (int t = 0; t < re_data; t++) {
                        try {
                            log.debug("本次处理数据：" + dataArr.getJSONObject(t).toString());
                            JSONObject dataJsonTwo = dataArr.getJSONObject(t);
                            //必定返回字段
                            String t_id = GetSFJV(dataJsonTwo, "_id"); //本条通话记录的唯一ID
                            String CALL_SHEET_ID = GetSFJV(dataJsonTwo, "CALL_SHEET_ID"); //本条通话记录的唯一ID（与_id值一致）
                            String CALL_NO = GetSFJV(dataJsonTwo, "CALL_NO");//主叫号码
                            String CALLED_NO = GetSFJV(dataJsonTwo, "CALLED_NO");//被叫号码
                            String CALL_ID = GetSFJV(dataJsonTwo, "CALL_ID"); //通话id
                            String CONNECT_TYPE = GetSFJV(dataJsonTwo, "CONNECT_TYPE"); //呼叫类型，值为 normal（普通来电）、dialout（外呼去 电）、transfer（来电转接）、dialTransfer（外呼转接）
                            String STATUS = GetSFJV(dataJsonTwo, "STATUS"); //处理状态，值为dealing（已接听）、notDeal（振铃未接 听）、queueLeak（排队放弃）、voicemail（已留言）、 leak（IVR放弃） 、blackList（黑名单）、limit(并发限制)
                            String OFFERING_TIME = GetSFJV(dataJsonTwo, "OFFERING_TIME"); //呼叫发起时间
                            String PBX = GetSFJV(dataJsonTwo, "PBX");//通话产生所在PBX的ID
                            String FILE_SERVER = GetSFJV(dataJsonTwo, "FILE_SERVER"); //录音服务器地址
                            String CALL_TIME_LENGTH = GetSFJV(dataJsonTwo, "CALL_TIME_LENGTH");//通话时长（未接通为0）

                            String BEGIN_TIME = GetSFJV(dataJsonTwo, "BEGIN_TIME"); //通话开始时间（只有已接听状态的才有值）
                            String END_TIME = GetSFJV(dataJsonTwo, "END_TIME"); //结束时间
                            String ACCOUNT_ID = GetSFJV(dataJsonTwo, "ACCOUNT_ID");//账户编号
                            String ACTION_ID = GetSFJV(dataJsonTwo, "ACTION_ID"); //调用外呼接口所传的ActionID
                            //String AGENT_NAME = GetSFJV(dataJsonTwo,"AGENT_NAME");
                            String CONSULT_TIME_LENGTH = GetSFJV(dataJsonTwo, "CONSULT_TIME_LENGTH"); //咨询时长
                            String CUSTOMER_ID = GetSFJV(dataJsonTwo, "CUSTOMER_ID"); //用户id
                            String CUSTOMER_NAME = GetSFJV(dataJsonTwo, "CUSTOMER_NAME");//定位用户名称
                            String DIRECTION = GetSFJV(dataJsonTwo, "DIRECTION"); //I呼入，O呼出
                            String DISPOSAL_AGENT = GetSFJV(dataJsonTwo, "DISPOSAL_AGENT"); //处理座席ID（历史原因创建的字段，如无用处可无视）
                            String DISTRICT = GetSFJV(dataJsonTwo, "DISTRICT"); //市
                            String DISTRICT_CODE = GetSFJV(dataJsonTwo, "DISTRICT_CODE"); //城市区号
                            String ERROR_MEMO = GetSFJV(dataJsonTwo, "ERROR_MEMO"); // 技能组编号
                            String EXTEN = GetSFJV(dataJsonTwo, "EXTEN"); //处理座席工号
                            String GW_CALL_SHEET_ID = GetSFJV(dataJsonTwo, "GW_CALL_SHEET_ID");
                            String HANGUP_USER = GetSFJV(dataJsonTwo, "HANGUP_USER"); //挂机方(字段值解释 ：agent 坐席挂机， customer 用户挂机，system 系统挂机)
                            //String HOLD_TIMES = GetSFJV(dataJsonTwo,"HOLD_TIMES");
                            String HOLD_TIME_LENGTH = GetSFJV(dataJsonTwo, "HOLD_TIME_LENGTH"); //保持时长
                            String IS_AUTO_CALL = GetSFJV(dataJsonTwo, "IS_AUTO_CALL"); //是否为批呼任务
                            String IVR_TIME_LENGTH = GetSFJV(dataJsonTwo, "IVR_TIME_LENGTH"); //从进入系统到进技能组中间消耗的时间
                            String LOCATION = GetSFJV(dataJsonTwo, "LOCATION"); // 最后一个IVR的信息
                            String LOCATION_ID = GetSFJV(dataJsonTwo, "LOCATION_ID"); //进入技能组时间
                            String LOCATION_NAME = GetSFJV(dataJsonTwo, "LOCATION_NAME"); //技能组名称
                            String LOGIN_TYPE = GetSFJV(dataJsonTwo, "LOGIN_TYPE"); //坐席外呼类型
                            //String MANYQUEUE_NUMBER = GetSFJV(dataJsonTwo, "MANYQUEUE_NUMBER"); //经过的技能组集合
                            //String ORIGIN_ID = GetSFJV(dataJsonTwo,"ORIGIN_ID");
                            //String PROCESS_STATUS = GetSFJV(dataJsonTwo,"PROCESS_STATUS");
                            String PROVINCE = GetSFJV(dataJsonTwo, "PROVINCE"); //省
                            String PROVINCE_CODE = GetSFJV(dataJsonTwo, "PROVINCE_CODE"); //省份code
                            String QUEUE_NAME = GetSFJV(dataJsonTwo, "QUEUE_NAME");//技能组名称
                            String QUEUE_TIME = GetSFJV(dataJsonTwo, "QUEUE_TIME"); //来电进入技能组的时间
                            String QUEUE_TIME_LENGTH = GetSFJV(dataJsonTwo, "QUEUE_TIME_LENGTH");//进入技能组时间
                            //String QUICK_HANGUP = GetSFJV(dataJsonTwo,"QUICK_HANGUP");
                            String QUICK_QUERY_NUM = GetSFJV(dataJsonTwo, "QUICK_QUERY_NUM"); //快接搜索号码
                            String RECORD_FILE_NAME = GetSFJV(dataJsonTwo, "RECORD_FILE_NAME"); //录音文件名
                            String REF_CALL_SHEET_ID = GetSFJV(dataJsonTwo, "REF_CALL_SHEET_ID");//转接类型通话，此字段记录之前一通通话记录的ID
                            //String REPEATCALLDEALAGENT = GetSFJV(dataJsonTwo,"REPEATCALLDEALAGENT");
                            String REPEAT_CALL = GetSFJV(dataJsonTwo, "REPEAT_CALL"); // 是否为24h或48h来电
                            String RING_TIME_LENGTH = GetSFJV(dataJsonTwo, "RING_TIME_LENGTH"); //被叫振铃时长
                            //String STATISTIC = GetSFJV(dataJsonTwo,"STATISTIC");
                            String THREEWAY_CALL_TIME_LENGTH = GetSFJV(dataJsonTwo, "THREEWAY_CALL_TIME_LENGTH"); //三方通话时长
                            //String biUpdateTime = GetSFJV(dataJsonTwo,"biUpdateTime");
                            //list
                            //String PRESSED_KEY_IN_PASSED_IVRS = GetSFJV(dataJsonTwo,"PRESSED_KEY_IN_PASSED_IVRS");

                            log.debug("开始处理数据编号：" + CALL_SHEET_ID)

                            //添加日志记录表获取到的数据
                            String recordSql = "INSERT INTO pa_dx_record(id, ACCOUNT_ID, ACTION_ID, BEGIN_TIME, CALLED_NO, CALL_ID, CALL_NO, CALL_SHEET_ID, CALL_TIME_LENGTH, CONNECT_TYPE, CONSULT_TIME_LENGTH, CUSTOMER_ID, CUSTOMER_NAME, DIRECTION, DISPOSAL_AGENT, DISTRICT, DISTRICT_CODE, END_TIME, ERROR_MEMO, EXTEN, FILE_SERVER, GW_CALL_SHEET_ID, HANGUP_USER, HOLD_TIME_LENGTH, IS_AUTO_CALL, IVR_TIME_LENGTH, LOCATION, LOCATION_ID, LOCATION_NAME, LOGIN_TYPE, OFFERING_TIME, PBX, PROVINCE, PROVINCE_CODE, QUEUE_NAME, QUEUE_TIME, QUEUE_TIME_LENGTH, QUICK_QUERY_NUM, RECORD_FILE_NAME, REF_CALL_SHEET_ID, REPEAT_CALL, RING_TIME_LENGTH, STATUS, THREEWAY_CALL_TIME_LENGTH, t_id) VALUES (uuid(), '" + ACCOUNT_ID + "', '" + ACTION_ID + "', '" + BEGIN_TIME + "', '" + CALLED_NO + "', '" + CALL_ID + "', '" + CALL_NO + "', '" + CALL_SHEET_ID + "', '" + CALL_TIME_LENGTH + "', '" + CONNECT_TYPE + "', '" + CONSULT_TIME_LENGTH + "', '" + CUSTOMER_ID + "', '" + CUSTOMER_NAME + "', '" + DIRECTION + "', '" + DISPOSAL_AGENT + "', '" + DISTRICT + "', '" + DISTRICT_CODE + "', '" + END_TIME + "', '" + ERROR_MEMO + "', '" + EXTEN + "', '" + FILE_SERVER + "', '" + GW_CALL_SHEET_ID + "', '" + HANGUP_USER + "', '" + HOLD_TIME_LENGTH + "', '" + IS_AUTO_CALL + "', '" + IVR_TIME_LENGTH + "', '" + LOCATION + "', '" + LOCATION_ID + "', '" + LOCATION_NAME + "', '" + LOGIN_TYPE + "', '" + OFFERING_TIME + "', '" + PBX + "', '" + PROVINCE + "', '" + PROVINCE_CODE + "', '" + QUEUE_NAME + "', '" + QUEUE_TIME + "', '" + QUEUE_TIME_LENGTH + "', '" + QUICK_QUERY_NUM + "', '" + RECORD_FILE_NAME + "', '" + REF_CALL_SHEET_ID + "', '" + REPEAT_CALL + "', '" + RING_TIME_LENGTH + "', '" + STATUS + "', '" + THREEWAY_CALL_TIME_LENGTH + "', '" + t_id + "')";
                            eliteBean.update(recordSql, "dataSource");


                            //是否接通,针对已经接通的数据检查event与record表是否存在对应的数据，不存在则新增，存在则不做处理
                            String CALLESTABLISHED = "0";
                            log.debug("通话时长:" + CALL_TIME_LENGTH + "|通话开始时间：" + BEGIN_TIME + "|通话结束时间:" + END_TIME);
                            if (CALL_TIME_LENGTH!="0" && BEGIN_TIME != "") {
                                CALLESTABLISHED = "1";

                                //外呼类型翻译
                                int Calltype2 = 0;
                                if (CONNECT_TYPE == "normal") {
                                    Calltype2 = 1;
                                } else if (CONNECT_TYPE == "dialout") {
                                    Calltype2 = 2;
                                }

                                //挂机类型翻译
                                int hanguptype2 = 0;
                                if (HANGUP_USER == "agent") {
                                    hanguptype2 = 2;
                                } else if (HANGUP_USER == "customer") {
                                    hanguptype2 = 1;
                                }

                                //设置默认处理组处理人，如后续未匹配到对应的处理人则默认为系统组
                                String Staff_id = "SELITE";
                                String DEFAULTROLEGROUP = "SYSTEM";
                                String agent_id = "999999";

                                //根据分机号查询是否匹配到集中作业平台，则使用查询的数据，未查询到则默认SYSTEM、999999、SELITE
                                List StaffList = eliteBean.chaxun_sql("select staff_id,DEFAULTROLEGROUP,agent_id from staff where left(agent_id,4)='" + EXTEN + "' limit 1", "dataSource");
                                if (StaffList.size() > 0) {
                                    Map StaffListMap = StaffList.get(0);
                                    Staff_id = StaffListMap.get("staff_id") == null ? '' : StaffListMap.get("staff_id");
                                    DEFAULTROLEGROUP = StaffListMap.get("DEFAULTROLEGROUP") == null ? '' : StaffListMap.get("DEFAULTROLEGROUP");
                                    agent_id = StaffListMap.get("agent_id") == null ? '' : StaffListMap.get("agent_id");

                                }

                                //查询record表是否存在该录音 存在则不新增,不存在新增
                                List GhbRecordList = eliteBean.chaxun_sql("select record_guid from record where initcallid='" + CALL_SHEET_ID + "'", "dataSource");
                                if (GhbRecordList.size() <= 0) {
                                    //新增到Record表
                                    log.debug("数据编号：" + CALL_SHEET_ID + "不存在Record表数据，开始新增Record");
                                    eliteBean.update("insert into Record(record_guid,DNIS,ANI,STARTTIME,ENDTIME, STAFF_ID,Agent_ID,calltype,documentpath,initcallid,ROLEGROUP_ID,hanguptype)values('" + CALL_SHEET_ID + "','" + CALLED_NO + "','" + CALL_NO + "','" + BEGIN_TIME + "','" + END_TIME + "','" + Staff_id + "','" + agent_id + "'," + Calltype2 + ",'','" + CALL_SHEET_ID + "','" + DEFAULTROLEGROUP + "','" + hanguptype2 + "')", "dataSource");
                                }

                                //查询是否存在通话记录数据， 存在则不新增,不存在新增
                                List GhbEventList = eliteBean.chaxun_sql("select event_guid from event where ATTACHEDDATA='" + CALL_SHEET_ID + "'", "dataSource");
                                if (GhbEventList.size() <= 0) {
                                    //新增event表数据
                                    log.debug("数据编号：" + CALL_SHEET_ID + "不存在Record表数据，开始新增Record");
                                    eliteBean.update("INSERT INTO event(EVENT_GUID, CALLTYPE, CUSTOMER_GUID, DNIS, ANI, TRANSFERFROM, TRANSFTERTO, CALLSTARTTIME, CALLENDTIME, HANGUPTYPE, WORKSTARTTIME, WORKENDTIME, CALLRESULT_ID, CALLRESULTREASON_ID, HANDLEBY_ID, HANDLEGROUP_ID, SATISFIEDRATE, STRINGFIELD1, STRINGFIELD2, ATTACHEDDATA, OBJECTIVESTATUS, CALLBEGINTIME, CALLESTABLISHED, RECORD_GUID, TRANSFERRESULT, COMMENTS, EXTENSION, AGENTID) VALUES (uuid(), " + Calltype2 + ", '', '" + CALLED_NO + "', '" + CALL_NO + "', '', '', '" + BEGIN_TIME + "', '" + END_TIME + "', " + hanguptype2 + ", '" + BEGIN_TIME + "', '" + END_TIME + "', 'CLOSE', '', '" + Staff_id + "', '" + DEFAULTROLEGROUP + "', NULL, 'jssoftphone', '', '" + CALL_SHEET_ID + "', '', null, '" + CALLESTABLISHED + "', '" + CALL_SHEET_ID + "', 0, '', '" + EXTEN + "', '" + agent_id + "')", "dataSource");
                                }


                            } else {
                                log.debug("数据编号：" + CALL_SHEET_ID + "未接通，本次不做处理");
                            }

                            //查询是否存在通话记录数据， 存在则不新增,不存在新增
                            List selectCus = eliteBean.chaxun_sql("select rec_guid from kh_record_expand where CallSheetID ='" + CALL_SHEET_ID + "'", "dataSource");
                            if (selectCus.size() == 0) {
                                log.debug("数据编号：" + CALL_SHEET_ID + "不存在Record表数据，开始新增Record");
                                String insertSQL = "INSERT INTO kh_record_expand (Rec_Guid, CallNo, CalledNo, CallSheetID, refCallSheetId, CallID, CallType, Ring, RingingDate, Begin, End, QueueTime, Agent, Exten, AgentName, Queue, State, CallState, ActionID, WebcallActionID, RecordFile, FileServer, Province, District, IVRKEY, AccountId, AccountName, CdrVar, DialoutStrVar, HangupPart, Sync_Time) VALUES (UUID(), '" + CALL_NO + "','" + CALLED_NO + "', '" + CALL_SHEET_ID + "', '', '" + CALL_ID + "', '" + CONNECT_TYPE + "', '','', '" + BEGIN_TIME + "', '" + END_TIME + "', '" + QUEUE_TIME + "', '" + EXTEN + "', '" + EXTEN + "', '', '" + LOCATION_NAME + "', '" + STATUS + "', '', '', '', '" + RECORD_FILE_NAME + "', '" + FILE_SERVER + "', '" + PROVINCE + "', '" + DISTRICT + "', '', '" + ACCOUNT_ID + "', '', '', '', '" + HANGUP_USER + "','"+beginTime+"')";
                                eliteBean.update(insertSQL, "dataSource");
                            }
                        } catch (Exception e1) {
                            log.error("数据处理错误", e1);
                        }
                    }
                }

                //查询结果页大于等于1000，
                if (re_data >= 1000) {
                    i = 0;
                    page = page + 1;
                } else {
                    i = 1;
                }
            }
        } catch (Exception e) {
            log.error("程序异常", e);
        }
    }


    public static String GetSFJV(inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
                log.debug("GetJV:" + Rev_Value);
            }
        }
        return Rev_Value;
    }
}
